
package com.eportal.action.background;

import com.eportal.action.BaseAction;
import com.eportal.base.BaseDAO;
import com.eportal.domain.*;
import com.eportal.params.background.mall.Tcommodity.CommodityParam;
import com.eportal.service.CBuildingService;
import com.eportal.service.CInstallUnitService;
import com.eportal.service.TCommodityService;
import com.eportal.service.UserWalletService;
import com.eportal.util.UploadUtil;
import com.eportal.util.WebUtil;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * 商品管理
 *
 */
public class TCommodityAction extends BaseAction implements ModelDriven<TCommodity> {

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private Logger log = Logger.getLogger(TCommodity.class);

    private Map<String, Object> result = new HashMap<String, Object>();
	@Resource(name="dao")
	private BaseDAO dao;
    @Autowired
    private TCommodityService tCommodityService;
    @Autowired
    private UserWalletService userWalletService;
    @Autowired
    private CInstallUnitService cInstallUnitService;
    @Autowired
    private CBuildingService cBuildingService;



    public String receiveLog(){
        return SUCCESS;
    }
    public String listView(){
        return SUCCESS;
    }
    public String addOrder() throws UnsupportedEncodingException{
    	String sid = (String)getRequest().getParameter("sid");
    	String cname = new String(getRequest().getParameter("cname").getBytes("ISO-8859-1"),"UTF-8");
    	//String cname = (String)getRequest().getParameter("cname");
    	String photo = (String)getRequest().getParameter("photo");
    	String price = (String)getRequest().getParameter("price");
    	String num = (String)getRequest().getParameter("num");
    	getRequest().setAttribute("sid", sid);
    	getRequest().setAttribute("cname", cname);
    	getRequest().setAttribute("photo", photo);
    	getRequest().setAttribute("price", price);
    	getRequest().setAttribute("num", num);
    	return SUCCESS;    }

    public String addRandomView(){
    	return SUCCESS;
    }
    public void page() throws Exception{
    	JqGridPager page = new JqGridPager();
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
		TuserWallet wallet = userWalletService.getOrcreateWallet(user.getrLevel(), user.getAgtCode(), user.getCommunityId());
		String walletId = wallet.getWid().toString();
		String ownerId = "301";
		StringBuffer where = new StringBuffer();
    	where.append(" t1.sid = t2.cid and t1.status='1'");
    	setPage(getRequest(), page);
    	page.setWhere(where.toString());
    	page.setSidx("t1.ctime");
    	page.setSord("desc");
        List<Map<String, Object>> list = tCommodityService.listView(page);
        jqGridQueryMap(Sysroles.class, getRequest(), list, getResponse(), page);
    }

    //提交订单
    public void subOrder() throws Exception{
    	String cmdid  = getRequest().getParameter("sid");
    	BigDecimal unitprice = new BigDecimal(getRequest().getParameter("price"));
   		BigDecimal comnumber = new BigDecimal(getRequest().getParameter("num"));
   		unitprice = unitprice.setScale(2, BigDecimal.ROUND_HALF_UP);
   		comnumber = comnumber.setScale(2, BigDecimal.ROUND_HALF_UP);
   		String addressid = "1";
   		String deliverrtype = "1";
   		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   		String ordernumber = sdf.format(new Date())+tCommodityService.getOrderBatchNummber();
   		BigDecimal paymoney = unitprice.multiply(comnumber).setScale(2, BigDecimal.ROUND_HALF_UP);
    	Sysopt user = (Sysopt) getSession().getAttribute("user");
		TuserWallet wallet = userWalletService.getOrcreateWallet(user.getrLevel(), user.getAgtCode(), user.getCommunityId());
		String ownerid = wallet.getWid().toString();
    	result = new HashMap<String, Object>();
    	try{
    		TCommodityOrder cmdorder = new TCommodityOrder();
    		cmdorder.setCmdid(cmdid);
    		cmdorder.setOrdernumber(ordernumber);
    		cmdorder.setUnitprice(unitprice);
    		cmdorder.setComnumber(comnumber);
    		cmdorder.setPaymoney(paymoney);
    		cmdorder.setAddressid(addressid);
    		cmdorder.setCustomerid(user.getSid().toString());
    		cmdorder.setOwnerid(ownerid);
    		cmdorder.setDeliverytype(deliverrtype);
    		cmdorder.setStatus("1");
    		cmdorder.setCtime(new Date());
    		cmdorder.setLastmodifytime(new Date());
    		dao.save(cmdorder);
			PayOrder payOrder = new PayOrder();
			payOrder.setOrderRelate("R0003");//R0003表示商城订单
			payOrder.setOrderRelateId(cmdorder.getsId().toString());
			payOrder.setPstate("1");
			payOrder.setAmount(new BigDecimal(String.valueOf(paymoney)));
			payOrder.setCusername(user.getSid().toString());
			payOrder.setUserType("1");
			payOrder.setCtime(new Timestamp(System.currentTimeMillis()));
			payOrder.setCname("商城订单:"+ordernumber);
    		String reqPreUrl = WebUtil.getReqPreUrl(getRequest());
			payOrder.setReturnUrl(reqPreUrl+"admin/redPacket_activeRedenv.action?redEnvId="+cmdorder.getsId().toString());
			payOrder.setNotifyUrl(reqPreUrl+"admin/redPacket_activeRedenvOut.action?redEnvId="+cmdorder.getsId().toString());
			dao.save(payOrder);
		    result.put("code", 1);
            result.put("msg", "操作成功");
            result.put("orderId", payOrder.getSid().toString());
            }catch (Exception e){
    		log.info(e.getMessage());
	   		result.put("code", 0);
	        result.put("msg", "订单提交失败");
    	}
    	responseBody(result);
    }

    public String setSendList(){
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	String rLevel = user.getrLevel().toString();
    	String param = "";
    	getRequest().setAttribute("rLevel", rLevel);
    	if("1".equals(rLevel)){
    		param = user.getAgtCode();
    	}
    	if("2".equals(rLevel)){
    		param = user.getCommunityId();
    	}
    	getRequest().setAttribute("prm", param);

    	return SUCCESS;
    }
    public String cmdDetail() throws Exception{
    	String sid = (String)getRequest().getParameter("sid");
    	List<Map<String, Object>> list = tCommodityService.cmdDetail(Long.valueOf(sid));
//    	String attrName = (String)list.get(0).get("ATTRIBUTENAME");
//    	String attrVal = (String)list.get(0).get("ATTRIBUTEVALUE");
    	getRequest().setAttribute("list", list);
    	return SUCCESS;
    }


    //激活红包
    public String activeRedenv() throws Exception{

    	return ERROR;
    }

    //激活红包外部通知地址
    public String activeRedenvOut() throws Exception{
    	String redEnvId = getRequest().getParameter("redEnvId");
    	result = new HashMap<String, Object>();
    	if((Integer)result.get("code")==1){
    		return "paySuccess";
    	}
    	return ERROR;
    }
        /**
         * 下架
         */
        public void off() throws Exception{
        	String sid  = getRequest().getParameter("sid");
       		Sysopt opt = (Sysopt) getSession().getAttribute("user");
        	result = new HashMap<String, Object>();
        	try{
        		result = tCommodityService.offMethod(Long.valueOf(sid),opt);
        	}catch (Exception e){
        		 log.info(e.getMessage());
		   		 result.put("code", 0);
		         result.put("msg", "下架红包失败");
        	}
        	responseBody(result);
        }
        //红包图片保存路径
        final static String REDENVPICPATH="/upload/redenv/";
       public String validateParm(String rName,String totalAmount,String totalNum,String reTimes,
    		   String effectiveDate,String isAllday,String isSendAll,String mainReType){
    	   String rst = "";
   		if("".equals(rName)||rName==null){
   				rst = "红包名称不能为空";
   				return rst;
	         }
		if(rName.length()>8){
				rst = "红包名称不能超过8个字符";
				return rst;
	         }
		if("".equals(totalAmount)||totalAmount==null){
				rst = "红包金额不能为空";
				return rst;
		}
		if(!isNumeric(totalAmount)){
				rst = "请输入正确的红包金额";
				return rst;
		}
		if("".equals(totalNum)||totalNum==null){
				rst = "红包个数不能为空";
				return rst;
		}
		if(!isNumeric(totalNum)){
				rst = "请输入正确的红包个数";
				return rst;
		}
		if("".equals(reTimes)||reTimes==null){
				rst = "红包领取次数不能为空";
				return rst;
		}
		if(!isNumeric(reTimes)){
				rst = "请输入正确的红包领取次数";
				return rst;
		}
		if("".equals(effectiveDate)||effectiveDate==null){
				rst = "红包有效期不能为空";
				return rst;
		}
		if(!isNumeric(effectiveDate)){
				rst = "请输入正确的红包有效期";
				return rst;
		}
		if("".equals(isAllday)||isAllday==null){
				rst = "红包发送时间不能为空";
				return rst;
		}
		if("".equals(isSendAll)||isSendAll==null){
				rst = "红包发放对象不能为空";
				return rst;
		}
		if("".equals(mainReType)||mainReType==null){
				rst = "红包类型不能为空";
				return rst;
		}
		return rst;
       }


   	public boolean isNumeric(String str){
   		   Pattern pattern = Pattern.compile("^(?!0(\\d|\\.0+$|$))\\d+(\\.\\d{1,2})?$");
   		   Matcher isNum = pattern.matcher(str);
   		   if( !isNum.matches() ){
   		       return false;
   		   }
   		   return true;
   		}

    public void uploadFile() throws Exception{
   		result = new HashMap<String, Object>();
		File file = getUpload();
		String fileUrl = "";
		if(file!=null){
	    	String fileName = getUploadFileName();
			result = UploadUtil.uplodeFile(file,fileName,REDENVPICPATH);
			if (!"1".equals(result.get("code").toString())) {
	        	responseBody(result);
	        	return;
			}
			fileUrl = result.get("agtAttr").toString();
			result.put("fileUrl", fileUrl);
		}else{
			result.put("code", 0);
			result.put("msg", "请选择图片");
		}
    	responseBody(result);
    }


    /**
     * =================================================
     * 商品管理API
     * Created by Saber on 2017/7/10 上午11:49
     * =================================================
     */

	public String addCommodityView(){

		return SUCCESS;
	}

    /**
     * 添加商品
     * @return
     */
    public void commodityAdd(){
        try {

            //从request中获取参数并封装为对象
            HttpServletRequest request=getRequest();
            CommodityParam param = new CommodityParam();
            BeanUtils.populate(param, request.getParameterMap());

            System.out.println("param = " + param.toString());


			File file = getPhotoM();
			if(file!=null){
				Map<String,String> m = uploadImg(file,getPhotoMFileName(), ",jpg,png,");
				if("1".equals(m.get("code"))){
					param.setPhoto(m.get("url"));
				}else{
						result.putAll(m);
						responseBody(result);
						return;
				}
			}else{
				result.put("code",0);
				result.put("msg","文件为空");
				responseBody(result);
				return;
			}
			StringBuffer attrPhotosUrls = new StringBuffer();
			file = getAttrPhoto1();
			if(file!=null){
				Map<String,String> m = uploadImg(file,getAttrPhoto1FileName(), ",jpg,png,");
				if("1".equals(m.get("code"))){
					attrPhotosUrls.append(m.get("url")).append(",");
				}else{
					/*	result.putAll(m);
						responseBody(result);
						return;*/
				}
			}
			file = getAttrPhoto2();
			if(file!=null){
				Map<String,String> m = uploadImg(file,getAttrPhoto2FileName(), ",jpg,png,");
				if("1".equals(m.get("code"))){
					attrPhotosUrls.append(m.get("url")).append(",");
				}else{
					/*	result.putAll(m);
						responseBody(result);
						return;*/
				}
			}
			file = getAttrPhoto3();
			if(file!=null){
				Map<String,String> m = uploadImg(file,getAttrPhoto3FileName(), ",jpg,png,");
				if("1".equals(m.get("code"))){
					attrPhotosUrls.append(m.get("url")).append(",");
				}else{
					/*	result.putAll(m);
						responseBody(result);
						return;*/
				}
			}
			file = getAttrPhoto4();
			if(file!=null){
				Map<String,String> m = uploadImg(file,getAttrPhoto4FileName(), ",jpg,png,");
				if("1".equals(m.get("code"))){
					attrPhotosUrls.append(m.get("url"));
				}else{
					/*	result.putAll(m);
						responseBody(result);
						return;*/
				}
			}
			param.setAttrPhoto(attrPhotosUrls.toString());
//            result.put("code",1);
//            result.put("msg","成功");
//            result.put("data","OK");

            result = tCommodityService.commodityAdd(param,getOptId(),getOwnerId());
            responseBody(result);
        }catch (Exception e){
            e.printStackTrace();
            log.error("商品添加异常",e);

            result.put("code",0);
            result.put("msg","添加商品异常");
            responseBody(result);
        }
    }


    /**
     * 获取ownerId
     * @Author Saber
     * @Date 2017/7/10 下午4:28
     * @return
     * @throws Exception
     */
    public String getOwnerId() throws Exception {
        Sysopt user = (Sysopt) getSession().getAttribute("user");
        TuserWallet wallet = userWalletService.getOrcreateWallet(user.getrLevel(), user.getAgtCode(), user.getCommunityId());
        String ownerid = wallet.getWid().toString();
        return ownerid;
    }

	/**
	 * 上传图片
	 * @param file
	 * @param fileName
	 * @param Limitext
	 * @return
	 */
	private Map<String, String> uploadImg(File file, String fileName,String Limitext) {
		Map result = new HashMap<String, String>();
		result.put("code", "-1");
		try {
			if (file.length() > 5120000) {
				result.put("msg", "不能大于5M");
				return result;
			}
			if (StringUtils.isBlank(fileName) || Limitext.indexOf(","+FilenameUtils.getExtension(fileName)+",")==-1) {
				result.put("msg", "请上传指定格式的文件");
				return result;
			}
			String url = File.separator+"upload"+File.separator+"file"+File.separator;
			String destDir = ServletActionContext.getRequest().getServletContext().getRealPath(url);
			if (!new File(destDir).exists()) {
				new File(destDir).mkdirs();
			}
			String filename = "commodity_"+UUID.randomUUID().toString().replace("-", "") + "."+FilenameUtils.getExtension(fileName);
			FileUtils.copyFile(file, new File(destDir, filename));
			result.put("code", "1");
			result.put("url",WebUtil.getReqPreUrl(getRequest())+(url+filename).replace(File.separator, "/"));
		} catch (IOException e) {
			log.error(this, e);
			result.put("msg", "上传传到服务器失败，请重试");
		}
		return result;
	}

	//大图
	private File photoM;
	private String photoMFileName ;  // 上传文件的名字 ,FileName 固定的写法
	private String photoMContentType ; //上传文件的类型， ContentType 固定的写法
	//小图1
	private File attrPhoto1;
	private String attrPhoto1FileName;
	private String attrPhoto1ContentType;
	//小图2
	private File attrPhoto2;
	private String attrPhoto2FileName;
	private String attrPhoto2ContentType;
	//小图3
	private File attrPhoto3;
	private String attrPhoto3FileName;
	private String attrPhoto3ContentType;
	//小图4
	private File attrPhoto4;
	private String attrPhoto4FileName;
	private String attrPhoto4ContentType;


	public File getPhotoM() {
		return photoM;
	}

	public void setPhotoM(File photoM) {
		this.photoM = photoM;
	}

	public String getPhotoMFileName() {
		return photoMFileName;
	}

	public void setPhotoMFileName(String photoMFileName) {
		this.photoMFileName = photoMFileName;
	}

	public String getPhotoMContentType() {
		return photoMContentType;
	}

	public void setPhotoMContentType(String photoMContentType) {
		this.photoMContentType = photoMContentType;
	}

	public File getAttrPhoto1() {
		return attrPhoto1;
	}

	public void setAttrPhoto1(File attrPhoto1) {
		this.attrPhoto1 = attrPhoto1;
	}

	public String getAttrPhoto1FileName() {
		return attrPhoto1FileName;
	}

	public void setAttrPhoto1FileName(String attrPhoto1FileName) {
		this.attrPhoto1FileName = attrPhoto1FileName;
	}

	public String getAttrPhoto1ContentType() {
		return attrPhoto1ContentType;
	}

	public void setAttrPhoto1ContentType(String attrPhoto1ContentType) {
		this.attrPhoto1ContentType = attrPhoto1ContentType;
	}

	public File getAttrPhoto2() {
		return attrPhoto2;
	}

	public void setAttrPhoto2(File attrPhoto2) {
		this.attrPhoto2 = attrPhoto2;
	}

	public String getAttrPhoto2FileName() {
		return attrPhoto2FileName;
	}

	public void setAttrPhoto2FileName(String attrPhoto2FileName) {
		this.attrPhoto2FileName = attrPhoto2FileName;
	}

	public String getAttrPhoto2ContentType() {
		return attrPhoto2ContentType;
	}

	public void setAttrPhoto2ContentType(String attrPhoto2ContentType) {
		this.attrPhoto2ContentType = attrPhoto2ContentType;
	}

	public File getAttrPhoto3() {
		return attrPhoto3;
	}

	public void setAttrPhoto3(File attrPhoto3) {
		this.attrPhoto3 = attrPhoto3;
	}

	public String getAttrPhoto3FileName() {
		return attrPhoto3FileName;
	}

	public void setAttrPhoto3FileName(String attrPhoto3FileName) {
		this.attrPhoto3FileName = attrPhoto3FileName;
	}

	public String getAttrPhoto3ContentType() {
		return attrPhoto3ContentType;
	}

	public void setAttrPhoto3ContentType(String attrPhoto3ContentType) {
		this.attrPhoto3ContentType = attrPhoto3ContentType;
	}

	public File getAttrPhoto4() {
		return attrPhoto4;
	}

	public void setAttrPhoto4(File attrPhoto4) {
		this.attrPhoto4 = attrPhoto4;
	}

	public String getAttrPhoto4FileName() {
		return attrPhoto4FileName;
	}

	public void setAttrPhoto4FileName(String attrPhoto4FileName) {
		this.attrPhoto4FileName = attrPhoto4FileName;
	}

	public String getAttrPhoto4ContentType() {
		return attrPhoto4ContentType;
	}

	public void setAttrPhoto4ContentType(String attrPhoto4ContentType) {
		this.attrPhoto4ContentType = attrPhoto4ContentType;
	}

	/**
     * ====================================================
     */


    private TCommodity tCommodity = new TCommodity();

	@Override
	public TCommodity getModel() {
		// TODO Auto-generated method stub
		return tCommodity;
	}


}
